package com.maxqaq.controller;

import com.maxqaq.constant.MessageConstant;
import com.maxqaq.result.Result;
import com.maxqaq.utils.QiniuUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@RestController
@RequestMapping("/upload")
public class UploadController {

    @PostMapping("/markdown")
    public Result markdown(@RequestParam("image") MultipartFile file) {
        if (file.isEmpty()) {
            return new Result(false, MessageConstant.UPLOAD_CHOOSE);
        }
        //获取文件名
        String originalFilename = file.getOriginalFilename();
        //获取文件后缀
        int index = originalFilename.lastIndexOf(".");
        String suffix = originalFilename.substring(index);
        String fileName = UUID.randomUUID().toString() + suffix;
        //开始上传
        try {
            QiniuUtil.uploadQiniu(file.getBytes(), fileName);
            return new Result(true, MessageConstant.UPLOAD_SUCCESS, fileName);
        } catch (Exception e) {
            return new Result(false, MessageConstant.PIC_UPLOAD_FAIL);
        }
    }

    @PostMapping("/webUpload")
    public Result webUpload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return new Result(false, MessageConstant.UPLOAD_CHOOSE);
        }
        //获取文件名
        String originalFilename = file.getOriginalFilename();
        //获取文件后缀
        int index = originalFilename.lastIndexOf(".");
        String suffix = originalFilename.substring(index);
        String fileName = UUID.randomUUID().toString().replace("-", "") + suffix;
        //开始上传
        try {
            QiniuUtil.uploadQiniu(file.getBytes(), fileName);
            return new Result(true, MessageConstant.UPLOAD_SUCCESS, fileName);
        } catch (Exception e) {
            return new Result(false, MessageConstant.PIC_UPLOAD_FAIL);
        }
    }



}
